#!/bin/bash
set -ex

[ -n "$AWS_ACCESS_KEY_ID" ] || {
  echo "AWS_ACCESS_KEY_ID is not set"
  exit 0
}

[ -n "$AWS_SECRET_ACCESS_KEY" ] || {
  echo "AWS_SECRET_ACCESS_KEY is not set"
  exit 0
}

[[ $1 =~ rke2\.(linux|windows)-.+\.tar\.gz ]] || {
  echo "First argument should be a dist bundle tarball" >&2
  exit 1
}

[[ $2 =~ rke2-images\..+\.tar\.zst ]] || {
  echo "Second argument should be a compressed airgap runtime image tarball" >&2
  exit 1
}

[ -n "$3" ] || {
  echo "Third argument should be a commit hash" >&2
  exit 1
}

umask 077

TMPDIR=$(mktemp -d)
cleanup() {
  exit_code=$?
  trap - EXIT INT
  rm -rf ${TMPDIR}
  exit ${exit_code}
}
trap cleanup EXIT INT

BUNDLE_NAME=$(basename $1 .tar.gz)-$3.tar.gz
(cd $(dirname $1) && sha256sum $(basename $1)) >${TMPDIR}/${BUNDLE_NAME}.sha256sum
cp $1 ${TMPDIR}/${BUNDLE_NAME}

TARBALL_NAME=$(basename $2 .tar.zst)-$3.tar.zst
(cd $(dirname $2) && sha256sum $(basename $2)) >${TMPDIR}/${TARBALL_NAME}.sha256sum
cp $2 ${TMPDIR}/${TARBALL_NAME}

for FILE in ${TMPDIR}/${BUNDLE_NAME}*; do
  aws s3 cp ${FILE} s3://rke2-ci-builds || exit 1
done

for FILE in ${TMPDIR}/${TARBALL_NAME}*; do
  aws s3 cp ${FILE} s3://rke2-ci-builds || exit 1
done
echo "Build uploaded" >&2
echo "https://rke2-ci-builds.s3.amazonaws.com/${BUNDLE_NAME}"
